package com.dm.learn.java.pattern.productor_consumer1;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.locks.ReentrantLock;

public class ThreadManager {
	public static Object signal = new Object();
	boolean bFull = false;// 仓库是否已经满了
	private List thingsList = new ArrayList();
	private final ReentrantLock lock = new ReentrantLock(true);
	private BlockingQueue q = new ArrayBlockingQueue(10);

	/**
	 * @Description: 生产
	 * @param
	 * @return void
	 * @throws
	 */
	public void product(String thing) throws Exception {
		synchronized (signal) {
			if (!bFull) {
				bFull = true;
				// 生产
				System.out.println("Product:");
				System.out.println("仓库已满,等待消费");
				thingsList.add(thing);
				signal.notify();// 通知消费者
			}
			signal.wait();// 自己进入signal待诏队列
		}
	}

	/**
	 * 
	 * @Description: 消费
	 * @param
	 * @return String
	 * @throws
	 */
	public String consumer() throws Exception {
		synchronized (signal) {
			if (!bFull) {
				signal.wait();// 进入signal待召队列，等待生产者的通知
			}
			bFull = false;
			// 读取buf 共享资源里面的东西
			System.out.println("consume");
			System.out.println("仓库已空，正等待生产...");
			signal.notify(); // 然后通知生产者
		}
		String result = "";
		if (thingsList.size() > 0) {
			result = thingsList.get(thingsList.size() - 1).toString();
			thingsList.remove(thingsList.size() - 1);
		}
		return result;
	}
}
